package com.ding;

import com.ding.dao.UserRepository;
import com.ding.pojo.Authority;
import com.ding.pojo.User;
import javassist.NotFoundException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.List;

@SpringBootApplication
public class HibernateApplication {

	public static void main(String[] args)
	{
		ConfigurableApplicationContext context = SpringApplication.run(HibernateApplication.class, args);
		UserRepository dao = context.getBean(UserRepository.class);
		//保存一个用户
		User user = new User("ding","666");
		user.addAuthority("user");
		user.addAuthority("admin");
		dao.save(user);

		//再保存一个用户
		user=new User("shi","888");
		user.addAuthority("user");
		dao.save(user);

		//查找用户,并将用户密码修改为123
		user = dao.query("ding");
		user.setPassword("123");

		try {
			dao.update(user);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}

		//查看密码信息是否修改成功
		user = dao.query("ding");
		System.out.println(user.getPassword());


		/*
		注意,如果级联采用懒加载的方式并且开启事务管理器,authorities是无法遍历的
		事务管理器特点是:在某个事务执行期开启一个session,当事务完成时就将session关闭
		所以,在session A中获取的user对象,在session A关闭后就无法加载级联的authorities
		 */
		//获取用户权限.
		List<Authority> authorities = user.getAuthorities();
		for (Authority authority : authorities) {
			System.out.println(authority);
		}
		//最后删除两个用户
		try {
			dao.delete("ding");
			dao.delete("shi");
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		context.close();
	}
}
